import {reactive} from "./reactive";
import {hasChanged, hasOwn, isObject} from "../shared/utils";
import {track,trigger} from "./effect";
import {TrackOpTypes, TriggerOpTypes} from "./operation";

const get = createGetter();
const set = createSetter();

function createGetter(){
  return function get(target,key,receiver/**←即new Proxy返回的proxy实例本身*/){
    const res = Reflect.get(target, key, receiver); //target[key]

    // console.log('用户对这个对象取值了', target, key);

    track(target, TrackOpTypes.GET, key); /** ←依赖收集*/

    if(isObject(res)){
      return reactive(res);
    }

    return res;
  }
}

function createSetter(){
  return function set(target,key,value,receiver/**←←原代理对象*/){
    const hadKey = hasOwn(target, key);
    const oldValue = target[key];
    const result = Reflect.set(target, key, value, receiver); //target[key] = value

    if(!hadKey){
      // console.log('属性的新增操作', target, key);
      trigger(target, TriggerOpTypes.ADD, key, value); /** ←触发更新*/
    }else if (hasChanged(value,oldValue)){
      // console.log('属性的修改操作', target, key);
      trigger(target, TriggerOpTypes.SET, key, value, oldValue); /** ←触发更新*/
    }
    //else 值没有变化 什么都不用做

    return result;
  }
}

/**
 * 此handler主要针对于对象和数组
 * @type {{set: set, get: get}}
 */
export const mutableHandler = {
  get,
  set
};

// export const mutableHandler2 = {
//   get:createGetter('xxx'),
//   set
// };
